package com.gitee.fsmxm.thinking.in.concurrent.basic;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * 并行 分治
 */
public class _13_ForkJoin_RecursiveTask {

    public static void main(String[] args) {

        ForkJoinPool pool = new ForkJoinPool(3);
        Fibonacci task = new Fibonacci(40);
        Integer result = pool.invoke(task);
        System.out.println(result);

    }

    /**
     * 斐波那契数列
     */
    public static class Fibonacci extends RecursiveTask<Integer> {
        private int n;
        public Fibonacci(int n) {
            this.n = n;
        }
        @Override
        protected Integer compute() {
            if (n <= 1) {
                return n;
            }
            Fibonacci f1 = new Fibonacci(n - 1);
            f1.fork();
            Fibonacci f2 = new Fibonacci(n - 2);
            return f2.compute() + f1.join();
        }
    }

}
